﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Reactive;
using System.Reactive.Linq;
using System.Drawing;
using System.IO;
using Util.ImageProcess;


namespace YLServerInterface.UserControls
{
    /// <summary>
    /// Interaction logic for ImageCutter.xaml
    /// </summary>
    public partial class ImageCutter : UserControl
    {

        ImageCutter()
        {
            InitializeComponent();
        }
        public ImageCutter(string ImgPath, string SaveImgPath, double RectWidth, double RectHeight)
            : this()
        {
            this.ImgPath = ImgPath;
            this.SaveImgPath = SaveImgPath;
            this.RectWidth = RectWidth;
            this.RectHeight = RectHeight;
        }
        public string ImgPath { get; set; }
        public string SaveImgPath { get; set; }
        /// <summary>
        ///截图宽度
        /// </summary>
        public double RectWidth { get; set; }
        /// <summary>
        /// 截图高度
        /// </summary>
        public double RectHeight { get; set; }
        public bool CanCut { get; private set; }
        /// <summary>
        /// 原始图片
        /// </summary>
        private BitmapImage bitmapImg;
        /// <summary>
        /// 初始时的宽度
        /// </summary>
        float rectOrignalWidth;
        /// <summary>
        /// 初始时的高度
        /// </summary>
        float rectOrignalHeight;
        /// <summary>
        /// 是否是第一次设置框框
        /// </summary>
        bool isRending = true;



        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //载入实际图片
            bitmapImg = new BitmapImage(new Uri(ImgPath));
            #region 使用缩略图，以提升速度
            var thumbnails = new BitmapImage();
            thumbnails.BeginInit();
            thumbnails.DecodePixelWidth = 200;
            thumbnails.UriSource = new Uri(ImgPath);
            thumbnails.EndInit();
            img.Source = thumbnails;
            #endregion
            #region 图片大小检查
            if (bitmapImg.PixelWidth < RectWidth || bitmapImg.PixelHeight < RectHeight)
            {
                CanCut = false;
                labError.Visibility = System.Windows.Visibility.Visible;
                return;
            }
            else
                CanCut = true;
            #endregion
        }

        #region 图片伸缩时
        private void img_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            updateRect(e);
        }
        /// <summary>
        /// 控件被改变大小是要改变框框，因为控件被改变的时候里面的图片大小也会被改变
        /// </summary>
        /// <param name="e"></param>
        private void updateRect(SizeChangedEventArgs e)
        {
            //会出现误差，所以干脆废弃
            //#region 改变rect的位置，按比例改变
            //if (e.PreviousSize.Width != 0 && e.PreviousSize.Height != 0)
            //{
            //    //var _x = e.NewSize.Width / e.PreviousSize.Width;
            //    //var _y = e.NewSize.Height / e.PreviousSize.Height;


            //    //rect.Margin = new Thickness(rect.Margin.Left * _x, rect.Margin.Top * _y, rect.Margin.Right, rect.Margin.Bottom);

            //    var wscale = (decimal)e.NewSize.Width / (decimal)e.PreviousSize.Width;
            //    var hscale = (decimal)e.NewSize.Height / (decimal)e.PreviousSize.Height;
            //    rect.Width = rect.Width * (double)wscale;
            //    rect.Height = rect.Height * (double)hscale;


            //    double dH = e.NewSize.Width - e.PreviousSize.Width;
            //    double dV = e.NewSize.Height - e.PreviousSize.Height;
            //    Canvas.SetLeft(rect, scale(Canvas.GetLeft(rect), e.PreviousSize.Width, e.NewSize.Width));
            //    Canvas.SetTop(rect, scale(Canvas.GetTop(rect), e.PreviousSize.Height, e.NewSize.Height));


            //}

            //#endregion
            #region  第一次时设置初始化框框大小
            if (isRending)
            {
                var imgWidth = bitmapImg.PixelWidth;
                var imgControlWidth = img.ActualWidth;
                double widthScale = imgControlWidth / imgWidth;

                var imgHeight = bitmapImg.PixelHeight;
                var imgControlHeight = img.ActualHeight;
                var heightScale = imgControlHeight / imgHeight;


                rectOrignalWidth = (float)widthScale * (float)RectWidth;
                rectOrignalHeight = (float)heightScale * (float)RectHeight;
                isRending = false;
                var exceptWidth = RectWidth * widthScale;
                var exceptHeight = RectHeight * heightScale;
                if (exceptWidth / imgControlWidth < 0.7 && exceptHeight / imgControlHeight < 0.7)
                {
                    var scale = RectWidth / RectHeight;
                    rect.Width = imgControlWidth * 0.5;
                    rect.Height = rect.Width / scale;
                }

                //移动到中心
                Canvas.SetLeft(rect, imgControlWidth / 2 - rect.Width / 2);
                Canvas.SetTop(rect, imgControlHeight / 2 - rect.Height / 2);

            }
            #endregion
        }
        #endregion

        #region 截图
        /// <summary>
        /// 执行剪切图片，并且根据传入名字进行保存
        /// </summary>
        /// <param name="outputImgName"></param>
        public void Cut()
        {
            #region 参数验证
            if (CanCut == false)
            {
                return;
            }
            if (SaveImgPath == "")
            {
                return;
            }
            #endregion
            using (Bitmap bitmap = new Bitmap(ImgPath))
            {
                //原先是1000  现在是100  那么x缩写10倍
                float xScalef = getXScaleF(bitmap.Width);
                float yScalef = getYScaleF(bitmap.Height);
                double left = Canvas.GetLeft(rect);
                double top = Canvas.GetTop(rect);
                //框框控件的信息
                PointF rectLeftTopPosition = new PointF((float)left, (float)top);
                //根据框框信息，计算出实际在图片中截取的左上角坐标
                PointF rectLeftTopAtImgPosition = getOrignalPosition(rectLeftTopPosition, xScalef, yScalef);
                //剪裁图片大小
                #region 框框变大后，原来截取的范围也要变大
                var rectXChangeScale = rect.Width / rectOrignalWidth;
                var rectYChangeScale = rect.Height / rectOrignalHeight;
                var imgSizef = new SizeF(
                    (float)(rectXChangeScale * RectWidth),
                    (float)(rectYChangeScale * RectHeight));
                #endregion
                RectangleF rectf = new RectangleF(rectLeftTopAtImgPosition, imgSizef);
                //复制图片指定位置
                using (var cutterBitmap = bitmap.Clone(rectf, bitmap.PixelFormat))
                {
                    //缩小分辨率，输出。
                    using (Bitmap emptyImg = new Bitmap((int)RectWidth, (int)RectHeight))
                    {
                        using (Graphics graphics = Graphics.FromImage(emptyImg))
                        {
                            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            graphics.DrawImage(cutterBitmap, new RectangleF(0, 0, emptyImg.Width, emptyImg.Height));
                            emptyImg.Save(SaveImgPath);
                        }
                    }
                }
            }
        }

        private float getXScaleF(int imgWidth)
        {
            return (float)((1.0f * imgWidth) / (1.0f * this.img.ActualWidth));//后者是控件呈现时候的宽度
        }
        private float getYScaleF(int imgHeight)
        {
            return (float)((1.0f * imgHeight) / (1.0f * this.img.ActualHeight));
        }
        private PointF getOrignalPosition(PointF p, float xScale, float yScale)
        {
            return new PointF(p.X * xScale, p.Y * yScale);
        }

        #endregion

        #region 滚轮截取框大小
        /// <summary>
        /// 鼠标滚轴增加减少因子
        /// </summary>
        private float rectXYScaleFactor = 1.05f;

        private void rect_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
            {
                rect.Width *= rectXYScaleFactor;
                rect.Height *= rectXYScaleFactor;
            }
            else
            {
                rect.Width /= rectXYScaleFactor;
                rect.Height /= rectXYScaleFactor;
            }
        }

        #endregion

    }
}
